<template>
  <div class="home-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户列表</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="form-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: 100%; margin-top: 20px" border stripe>
        <el-table-column label="序号" width="100" align="center">
          <template slot-scope="scope">{{scope.$index+1+queryInfo.num*(queryInfo.page-1)}}</template>
        </el-table-column>

        <el-table-column prop="nickName" label="用户名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120">
          <template slot-scope="scope">
            {{scope.row.createTime | DateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="handleTypeChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="用户角色"> </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="open_editForm(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <!-- <el-button type="danger" icon="el-icon-delete" size="mini" @click="confirm_del(scope.row.id)"></el-button> -->
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="openSetRoleDialog(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page" :page-size="queryInfo.num" layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="80px" :rules="addFormRules" ref="addFormref" :model="addUserform">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="addUserform.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input type="password" autocomplete="off" v-model="addUserform.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="addUserform.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="addUserform.roleId" placeholder="请选择">
            <el-option v-for="item in roleOpt" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddUserForm('addFormref')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="editVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="80px" :rules="editFormRules" ref="editFormref" :model="editUserform">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="editUserform.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="editUserform.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="editUserform.roleId" placeholder="请选择">
            <el-option v-for="item in roleOpt" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUserForm('editFormref')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {

  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    return {
      queryInfo: {
        query: '',
        num: 10,
        page: 1
      },
      total: 0,
      userList: [],
      roleOpt: [],
      dialogVisible: false,
      editVisible: false,
      addUserform: {
        username: '',
        email: '',
        roleId: '',
        nickName: '',
        password: ''
      },
      editUserform: {
        id: 0,
        username: '',
        email: '',
        roleId: '',
        nickname: ''
      },
      addFormRules: {
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '密码的长度应为3-10个字符'
        }
        ],
        nickName: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ],
        roleId: [{
          required: true,
          message: '请选择角色',
          trigger: 'blur'
        }]
      },
      editFormRules: {
        nickname: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ]
        // roleId: [{
        //   required: true,
        //   message: '请选择角色',
        //   trigger: 'blur'
        // }]
      }
    }
  },
  created () {
    this.getUserList()
  },
  computed: {},
  methods: {
    async getUserList () {
      const {
        data: res
      } = await this.$http.post('/userinfo/select', this.queryInfo)
      if (res.code !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data
      this.total = res.count
    },
    openDialog () {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.resetAddForm('addFormref')
        this.getRoleList()
      })
    },
    async getRoleList () {
      const {
        data: res
      } = await this.$http.post('/role/getAllRole')
      if (res.code !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.roleOpt = res.data
    },

    // 提交新增的表单
    submitAddUserForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const {
            data: res
          } = await this.$http.post('/userinfo/addUser', this.addUserform)
          if (res.code !== 200) {
            this.$message.error(res.msg)
            this.dialogVisible = false
            return false
          }
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.getUserList()
        } else {
          this.$message.error('添加用户失败！')
          this.dialogVisible = false
          return false
        }
      })
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    handleSizeChange (val) {
      this.queryInfo.num = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.page = val
      this.getUserList()
    },
    async handleTypeChange (obj) {
      const { data: res } = await this.$http.post('/userinfo/updateState', {
        id: obj.id,
        state: obj.mg_state
      })
      if (res.code !== 200) {
        obj.mg_state = !obj.mg_state
        return this.$message.error(res.msg)
      }
      return this.$message.success('修改用户状态成功！')
    },
    async open_editForm (id) {
      this.editVisible = true
      this.getRoleList()
      const {
        data: res
      } = await this.$http.post('/userinfo/detail', {
        id: id
      })
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      const data = res.data
      data.nickname = data.nickName
      this.editUserform = res.data
    },
    submitEditUserForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const {
            data: res
          } = await this.$http.post('/userinfo/updateInfo', this.editUserform)
          if (res.code !== 200) {
            this.$message.error(res.msg)
            this.editVisible = false
            return false
          }
          this.$message.success('编辑用户成功')
          this.editVisible = false
          this.getUserList()
        } else {
          this.$message.error('编辑用户失败')
          this.editVisible = false
          return false
        }
      })
    }
  }
}

</script>
<style lang="less" scoped>
  .form-container {
    margin-top: 20px;
  }

</style>
